import { observable, action } from 'mobx';
import { WeaForm } from 'comsMobx'
import { WeaTools, WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import { Modal, message } from "antd"
import { toJS } from 'mobx';
import * as  Apis from '../apis/project';
import PrjTaskListTable from '../components/comp/prjTaskListTable/index';

export class AddProjectStore {
    @observable title = getLabel(15007, "新建项目");
    @observable selectedKey = "prjinfo";
    @observable form = new WeaForm();
    @observable nameremind = '';

    @observable visible = false;
    @observable conditionDatas = {
        taskinfo: [],
        fieldinfo: [],
        prjid: "",
        rightMenu: [],
        userid: "",
        taskViewAttr: ""
    };

    validateRules = {};  //校验规则
    @observable selectedRowKey = [];
    @observable spinning = false;
    @observable templetid = "";
    @observable stageInfo = {
        stageKey: 0,
        stageColumns: [],
        stageColumnDatas: [],
        selectedRowKeys: [],
        selectedDatas: {},
        canedit:false
    }
    @observable parentid = 0;

    @observable isTimeShow = '1'; //任务时间字段是否启用

    @action
    handleShareDialog = (bool, params) => {
        this.visible = bool;
        this.selectedKey = "prjinfo";
        this.selectedRowKey = [];
        this.clearStageStatus();
        if(bool && params.prjid){
            this.parentid = params.prjid;
        }else{
            this.parentid = 0;
        }
        if (bool) {
            this.templetid = params.templetid;
            this.getAddCondition(params);
        }
    }

    changeTab = (key) => {
        this.selectedKey = key
    }
    //初始化form
    getAddCondition = (params = {}) => {
        this.form = new WeaForm();
        let _this = this;
        WeaTools.callApi('/api/proj/pcproject/getProjectInfo', 'GET', params).then(data => {
            this.isTimeShow = data.isTimeShow;
            this.conditionDatas = {
                taskinfo: _this.addInitKeytoDatas(toJS(data.taskinfo)),
                fieldinfo: data.fieldinfo,
                prjid: data.prjid,
                rightMenu: data.rightMenus,
                userid: data.userid,
                taskViewAttr: data.taskViewAttr,
            };
            if (data && data.templetName) {
                this.title = data.templetName;
            } else {
                this.title = getLabel(15007, "新建项目");
            }
            this.getPrjTempletStageList();
            _this.form && !_this.form.isFormInit && _this.form.initFormFields(data.fieldinfo);
        })
    }
    //更新数据
    setFormFields = (value) => {
        this.form.updateFields(value, false);
    }
    //保存校验规则
    setValidate = (params = {}) => {
        this.validateRules = params;
    }
    //保存list
    saveListDatas = (datas) => {
        this.conditionDatas = {
            ...this.conditionDatas,
            taskinfo: datas
        }
    }
    addNewListDatas = () => {
        const data = {
            "endtime": "",
            "hrmid": "",
            "budget": "0.000",
            "workday": "0",
            "begintime": "",
            "pid": "0",
            "realid": "0",
            "beftaskname": "",
            "id": "",
            "beftaskid": "",
            "name": getLabel(83982, "新的任务"),
            "hrmname": "",
            "begindate": "",
            "enddate": ""
        };
        let newtaskinfo = toJS(this.conditionDatas.taskinfo);
        newtaskinfo.push(data);
        this.saveListDatas(this.addKeytoDatas(newtaskinfo));
    }
    addInitKeytoDatas(datas) {
        let _datas = datas.map((data, i) => {
            let _data = { ...data };
            _data.key = i + 1;
            _data.rowIndex = i + 1;
            return _data
        })
        return _datas
    }

    addKeytoDatas(datas) {
        let _datas = datas.map((data, i) => {
            let _data = { ...data };
            _data.rowIndex = i + 1;
            return _data
        })
        return _datas
    }

    saveRowKeys = (arr) => {
        this.selectedRowKey = arr;
    }
    //删除
    deleListDatas = () => {
        let newtaskinfo = this.addKeytoDatas(toJS(this.conditionDatas.taskinfo));

        let _datas = [].concat(newtaskinfo);
        toJS(this.selectedRowKey).map(key => {
            _datas = _datas.filter(data => Number(data.rowIndex) !== key)
        });
        const newdatas = this.changeBeforeTask(_datas);
        this.saveListDatas(this.addKeytoDatas(newdatas));
        this.selectedRowKey = [];
    }
    //change 前置任务
    changeBeforeTask = (datas) => {
        let _datas = [].concat(datas);
        _datas.map(item => {
            if (item.beftaskid && item.beftaskid !== "0") {
                let bool = true;
                for (let i = 0; i < _datas.length; i++) {
                    if (_datas[i].rowIndex == item.beftaskid) {
                        item.beftaskid = _datas[i].rowIndex;
                        item.beftaskname = _datas[i].name;
                        bool = true;
                        return;
                    } else {
                        bool = false
                    }
                }
                if (!bool) {
                    item.beftaskid = "0";
                    item.beftaskname = "";
                }
            }

        });
        return _datas;
    }
    saveAddProject = (params = {}) => {
        const { isreflesh, checkProps } = params;
        const { pass } = checkProps;
        let _this = this;
        this.form.validateForm().then(f => {
            if (f.isValid&&pass) {
                if(this.checkRepeat()){
                    let newParams = { ...this.form.getFormParams(), ...params };
                    if(this.parentid > 0){
                        newParams = { ...this.form.getFormParams(), ...params, parentid : this.parentid };
                    }
                    let par = { ...newParams, method: "add" };
                    if (this.checkTaskInfo()&&this.checkTask()) {
                        par.subfields = JSON.stringify(toJS(this.conditionDatas.taskinfo));
                        par.stagelist = JSON.stringify(toJS(this.stageInfo.stageColumnDatas));
                        this.spinning = true;
                        WeaTools.callApi('/api/proj/pcproject/doPrjOperation', 'POST', par).then(data => {
                            _this.spinning = false;
                            if (data.success) {
                                message.success(getLabel(101, "项目") + getLabel(383317, "新建成功"));
                                if (isreflesh) {       //卡片里面的新建
                                    window._table.reLoad();
                                } else {      //新建项目的新建,卡片跳转
                                    weaHistory.push({
                                        pathname: '/main/prj/projectCard?prjid=' + data.prjid
                                    });
                                }
                                _this.handleShareDialog(false);
                            } else {
                                // Modal.warning({
                                //     title: getLabel(15172, "系统提示"),
                                //     content: data.msg,
                                // });
                                message.error(data.msg);
                            }
                        })
                    }
                }

            } else {
                f.showErrors();
            }
            if(this.selectedKey=='prjinfo'&&f.isValid==true&&(this.checkTask()==false||this.checkStage()==false)){
                message.error(getLabel(15859,"必要信息不完整！"));
            }
            if(this.selectedKey=='sublist'&&this.checkTask()==true&&(f.isValid==false||this.checkStage()==false)){
                message.error(getLabel(15859,"必要信息不完整！"));
            }
            if(this.selectedKey=='stagelist'&&this.checkStage()==true&&(f.isValid==false||this.checkTask()==false)){
                message.error(getLabel(15859,"必要信息不完整！"));
            }
        });

    }

    checkRepeat = () => {
		let repeat = true;
		let datas = toJS(this.stageInfo.stageColumnDatas);
		datas && datas.length>0 && datas.map((d1,i1) => {
			if(repeat){
				datas && datas.length>0 && datas.map((d2,i2) => {
					if(i1 !== i2 && d1.name == d2.name){
                        // Modal.warning({
                        //     title: getLabel(15172, "系统提示"),
                        //     content: getLabel('387703',"阶段名称重复！"),
                        // });
                        message.error(getLabel('387703',"阶段名称重复！"));
						repeat =  false;
					}
				})
            }
        })
        
		return repeat;
    }
    
    checkTask = () =>{
        let checked = true;
        let datas = toJS(this.conditionDatas.taskinfo);
        datas && datas.length>0 && datas.map((d1,i1) => {
            if(checked){
                if(d1.name == "" ){
                    checked = false;
                    // Modal.warning({
                    //     title: getLabel(15172, "系统提示"),
                    //     content:  getLabel('387707',"任务名称必填！"),
                    // });
                }else if(d1.stageid == ""){
                    checked = false;
                    // Modal.warning({
                    //     title: getLabel(15172, "系统提示"),
                    //     content:  getLabel('387708',"阶段必填！"),
                    // });
                }else if(d1.hrmid == ""){
                    checked = false;
                    // Modal.warning({
                    //     title: getLabel(15172, "系统提示"),
                    //     content:  getLabel('387709',"任务负责人必填！"),
                    // });
                }else{
                    let datas2 = toJS(this.stageInfo.stageColumnDatas);
                    let finded = false;
                    datas2 && datas2.length>0 && datas2.map((d2,i2) => {
                        if(d1.stageid == d2.id ){
                            finded = true;
                        }
                    })
                    if(!finded){
                        checked =false;
                        // Modal.warning({
                        //     title: getLabel(15172, "系统提示"),
                        //     content:  getLabel('387708',"阶段必填！"),
                        // });
                    }
                }
            }
        });
        return checked;
    }

    checkStage = () => {
		let checked = true;
		let datas = toJS(this.stageInfo.stageColumnDatas);
		datas && datas.length>0 && datas.map((d1,i1) => {
			if(checked){
                if(d1.name == ""){
                    checked = false;
                }
            }
        })      
		return checked;
    }

    checkTaskInfo = () => {
        const taskinfo  = this.conditionDatas.taskinfo;
        let checked = true;
        taskinfo && taskinfo.length>0 && taskinfo.map( item => {
            if(item.name && item.name == ""){
                Modal.warning({
                    title: getLabel(15172, "系统提示"),
                    content: "任务信息不完成！",
                });
                checked = false;
            }else if(item.stageid && item.stageid == ""){
                Modal.warning({
                    title: getLabel(15172, "系统提示"),
                    content: getLabel(15859, "任务信息不完成！"),
                });
                checked = false;
            }else if(item.hrmid && item.hrmid == ""){
                Modal.warning({
                    title: getLabel(15172, "系统提示"),
                    content: getLabel(15859, "任务信息不完成！"),
                });
                checked = false;
            }
        })
        return checked;
    }
    clearStatus = () => {
        this.selectedKey = "prjinfo";
        this.conditionDatas = {
            taskinfo: [],
            fieldinfo: [],
            prjid: "",
            rightMenu: [],
            userid: "",
            taskViewAttr: ""
        };
        this.validateRules = {};  //校验规则
        this.selectedRowKey = [];
    }

    getPrjTempletStageList = (params = {}) => {
        this.loading = true;
        let newParams = { actionType: "add", prjid: this.templetid, ...params };
        Apis.getPrjTempletStageList(newParams).then(data => {
            this.stageInfo.stageColumns = data.columns;
            this.stageInfo.stageColumnDatas = data.columnDatas;
            this.stageInfo.canedit = data.canedit;
            if(this.stageInfo.stageColumnDatas.length==0){
                this.stageInfo.stageKey++;
                let stageColumnDatas = [{  
                    id: "new_" + this.stageInfo.stageKey,
                    name: getLabel('387710',"新的阶段"),
                    description : ""}];
                this.stageInfo.stageColumnDatas = stageColumnDatas;
            }   
            this.rightMenu = data.rightMenus;
            this.loading = false;
        })
    }

    onRowSelect = (sRowKeys, rows, dataIndex, selectedDatas) => {
        this.stageInfo.selectedRowKeys = sRowKeys;
        if (selectedDatas) {
            this.stageInfo.selectedDatas = selectedDatas;
        }
    }

    onChange = (datas, a, v, b) => {
        let newDatas = [];
        this.stageInfo.stageKey++;
        datas.map((item) => {
            if (typeof (item.id) == "undefined") {
                newDatas.push({
                    id: "new_" + this.stageInfo.stageKey,
                    ...item,
                    name: ""
                });
            } else {
                newDatas.push(item);
            }
            
        });
        let newTaskDatas = [];
        let taskDatas = toJS(this.conditionDatas.taskinfo);
        taskDatas.map((item)=>{
            let find = false;
            newDatas.map((item2)=>{
                if(item.stageid !== "" && item.stageid == item2.id){
                    find = true;
                }
            });
            if(!find){
                newTaskDatas.push({...item,stageid:""});
            }else{
                newTaskDatas.push(item);
            }
        });
        this.conditionDatas.taskinfo = newTaskDatas;
        this.stageInfo.stageColumnDatas = newDatas;
    }

    clearStageStatus = () => {
        let _canedit = this.stageInfo.canedit;
		this.stageInfo = {
			stageColumns: [],
			stageColumnDatas: [],
			selectedRowKeys: [],
			selectedDatas: {},
            canedit:_canedit,
            stageKey:0
		}
    }

}
